
package com.cn.xiaonuo.slbfinances.slborders.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.DateUtils;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlShopWallet;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlbShop;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlShopWalletOrder;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlWithdrawalDetailed;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlShopWalletOrderMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlWithdrawalDetailedMapper;
import com.cn.xiaonuo.slbfinances.slborders.param.SlWithdrawalDetailedParam;
import com.cn.xiaonuo.slbfinances.slbshopes.mapper.SlbShopMapper;
import com.cn.xiaonuo.slbfinances.slbwallets.mapper.SlbShopWalletMapper;
import com.cn.xiaonuo.slbfinances.slpabank.entity.SlPaMember;
import com.cn.xiaonuo.slbfinances.slpabank.mapper.SlPaMemberMapper;
import com.cn.xiaonuo.tcrfinance.payconfig.enums.HpcEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cn.xiaonuo.slbfinances.slborders.service.SlWithdrawalDetailedService;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**   
 *  
 * @Description:  商家提现明细每日汇总表——SERVICEIMPL
 * @Author:       luyangyang   
 * @CreateDate:   SlWithdrawalDetailed
 * @Version:      V1.0
 *    
 */
@Slf4j
@Service
public class SlWithdrawalDetailedServiceImpl extends ServiceImpl<SlWithdrawalDetailedMapper, SlWithdrawalDetailed>  implements SlWithdrawalDetailedService {
	
	@Autowired
	public SlWithdrawalDetailedMapper slWithdrawalDetailedMapper;
	@Autowired
	public SlShopWalletOrderMapper slShopWalletOrderMapper;
	@Autowired
	public SlPaMemberMapper slPAMemberMapper;
	@Autowired
	private SlbShopMapper slbShopMapper;
	@Autowired
	private SlbShopWalletMapper slbShopWalletMapper;

	/**
	 * 搜了宝订单管理--商家提现明细
	 * @param param
	 * @return
	 */
	@Override
	@DataSource(name = "jyb_soole_data_hn")
	public BusinessMessage withdrawalDetailed(SlWithdrawalDetailedParam param){
		BusinessMessage message = new BusinessMessage();
		SlWithdrawalDetailed slWithdrawalDetailed=new SlWithdrawalDetailed();
		BeanUtil.copyProperties(param,slWithdrawalDetailed);
		Integer pageSize = param.getPageSize();
		Integer pageNo = param.getPageNo();
		if (null == pageNo || pageNo < 1) {
			pageNo=1;
		}
		if (null == pageSize || pageSize < 1) {
			pageSize=10;
		}
		LambdaQueryWrapper<SlWithdrawalDetailed> wrapper = new LambdaQueryWrapper<>();
		if (ObjectUtils.isNotEmpty(param.getSettlementBeginTime()) || ObjectUtils.isNotEmpty(param.getSettlementEndTime())) {
			wrapper.between(SlWithdrawalDetailed::getSettlementTime, param.getSettlementBeginTime(), param.getSettlementEndTime());
		}
		if (ObjectUtils.isNotEmpty(param.getBeginTime()) || ObjectUtils.isNotEmpty(param.getEndTime())) {
			wrapper.between(SlWithdrawalDetailed::getWithdrawalTime, param.getBeginTime(), param.getEndTime());
		}
		if (ObjectUtils.isNotEmpty(param.getWithdrawalNo())) {
			wrapper.eq(SlWithdrawalDetailed::getWithdrawalNo, param.getWithdrawalNo());
		}
		if (ObjectUtils.isNotEmpty(param.getWalletOrderId())) {
			wrapper.eq(SlWithdrawalDetailed::getWalletOrderId, param.getWalletOrderId());
		}
		if (ObjectUtils.isNotEmpty(param.getWithdrawalStatus())) {
			wrapper.eq(SlWithdrawalDetailed::getWithdrawalStatus, param.getWithdrawalStatus());
		}
		if (ObjectUtils.isNotEmpty(param.getUserId())) {
			wrapper.eq(SlWithdrawalDetailed::getUserId, param.getUserId());
		}
		wrapper.orderByDesc(SlWithdrawalDetailed::getId);
		slWithdrawalDetailed.setSumStatus(Convert.toStr(HpcEnum.DRAWING_STATUS.getCode()));
		BigDecimal drawingAmount=slWithdrawalDetailedMapper.sumAmount(slWithdrawalDetailed);
		slWithdrawalDetailed.setSumStatus(Convert.toStr(HpcEnum.DRAWING_STATUS_OK.getCode()));
		BigDecimal drawFinishAmount=slWithdrawalDetailedMapper.sumAmount(slWithdrawalDetailed);
		Map<String,Object> map=new HashMap<>();
		Page<SlWithdrawalDetailed> page = slWithdrawalDetailedMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
		map.put("drawingAmount",drawingAmount);
		map.put("drawFinishAmount",drawFinishAmount);
		map.put("sumAmount",drawingAmount.add(drawFinishAmount));
		map.put("pageInfo",page);
		//3.返回数据
		message.setData(map);
		message.setSuccess(true);
		message.setMessage("操作成功");
		return message;

	}

	/**
	 * 搜了宝订单管理--商家提现明细定时
	 * @return
	 */
	@Override
	@DataSource(name = "jyb_soole_data_hn")
	public BusinessMessage withdrawalDetailedTask(){
		log.info("搜了宝商家提现明细定时任务开始......");
		BusinessMessage message = new BusinessMessage();
		Integer pageSize =1000;
		Integer pageNo = 1;
		PageInfo<SlShopWalletOrder> page;
		PageHelper.startPage(pageNo,pageSize);
		int i=1;
		do {
			List<SlShopWalletOrder> list= slShopWalletOrderMapper.queryList();
			page = new PageInfo<>(list);
			if (CollectionUtils.isEmpty(page.getList())) {
				break;
			}
			for (SlShopWalletOrder xlShopWalletOrder : page.getList()) {
				try {
					if (!org.springframework.util.ObjectUtils.isEmpty(xlShopWalletOrder)){
						List<SlWithdrawalDetailed> slWithdrawalList =this.selectListByUserId(xlShopWalletOrder.getUserId());
						log.info("shopWalletOrderId:{},userId:{},执行行数{}",xlShopWalletOrder.getId(),xlShopWalletOrder.getUserId(),i);
						SlPaMember slPaMember=slPAMemberMapper.selectOne(new QueryWrapper<>(new SlPaMember() {{
							setSlUserId(xlShopWalletOrder.getUserId());
						}}));
						if(slPaMember==null){
							slPaMember=new SlPaMember();
						}

						SlbShop slShop=slbShopMapper.getByUserId(xlShopWalletOrder.getUserId());
						if(slShop==null){
							 slShop=slbShopMapper.selectOne(new QueryWrapper<>(new SlbShop() {{
								 setOwnerId(xlShopWalletOrder.getUserId());
							 }}));
						}
						SlShopWallet slShopWallet = slbShopWalletMapper.selectOne(new QueryWrapper<>(new SlShopWallet() {{
							setUserId(xlShopWalletOrder.getUserId());
							setType(0);
						}}));
						BigDecimal addTotalAmount=xlShopWalletOrder.getBalance();
						if(slWithdrawalList.size()>0){
							SlWithdrawalDetailed slWithdrawalDetailed=slWithdrawalList.get(0);
							addTotalAmount=addTotalAmount.add(slWithdrawalDetailed.getAddTotalAmount());
						}
						Date settlementTime=null;
						if(xlShopWalletOrder.getPayTime()!=null){
							settlementTime=DateUtils.stringToDate(xlShopWalletOrder.getPayTime());
						}
						SlWithdrawalDetailed executeReq = SlWithdrawalDetailed.builder()
								.userId(xlShopWalletOrder.getUserId())
								.walletOrderId(xlShopWalletOrder.getId())
								.userName(slPaMember.getRealName())
								.shopId(slShop.getId())
								.shopName(slShop.getName())
								.withdrawalOrderId(Convert.toStr(xlShopWalletOrder.getOrderId()))
								.withdrawalNo(xlShopWalletOrder.getWithdrawalNo())
								.totalAmount(xlShopWalletOrder.getBalance())
								.bankCardCode(slPaMember.getBankCardCode())
								.bankName(slPaMember.getBankName())
								.openBranchBank(slPaMember.getOpenBranchBank())
								.withdrawalStatus(Convert.toStr(xlShopWalletOrder.getPayStatus()))
								.withdrawalTime(DateUtils.stringToDate(xlShopWalletOrder.getCreateTime()))
								.settlementTime(settlementTime)
								.addTotalAmount(addTotalAmount)
								.shopAvailableAmount(slShopWallet.getAvailableBalance())
								.build();
						slWithdrawalDetailedMapper.insert(executeReq);
						i=i+1;
					}
				} catch (Exception e) {
					log.error("shopWalletOrderId:{},userId:{},message:{} ",xlShopWalletOrder.getId() ,xlShopWalletOrder.getUserId(),e.getMessage());
					e.printStackTrace();
				}
			}
		} while (page.isHasNextPage());
		log.info("搜了宝商家提现明细定时任务结束......");
		//3.返回数据
		message.setData(null);
		message.setSuccess(true);
		message.setMessage("操作成功");
		return message;

	}
	/**
	 * 获取会员信息
	 *
	 * @author 卢阳阳
	 * @date 2022-12-23 14:55:13
	 */
	@DataSource(name = "jyb_soole_data_hn")
	public List<SlWithdrawalDetailed> selectListByUserId(Integer userId) {
		LambdaQueryWrapper<SlWithdrawalDetailed> slWithdrawalWrapper = new LambdaQueryWrapper<>();
		slWithdrawalWrapper.eq(SlWithdrawalDetailed::getUserId, userId);
		slWithdrawalWrapper.orderByDesc(SlWithdrawalDetailed::getId).last(" limit 1");
		List<SlWithdrawalDetailed> slWithdrawalList = slWithdrawalDetailedMapper.selectList(slWithdrawalWrapper);
		return slWithdrawalList;
	}
	@Override
	@DataSource(name = "jyb_soole_data_hn")
	public void excelWithdrawal(HttpServletResponse response, SlWithdrawalDetailedParam param){
		SlWithdrawalDetailed slWithdrawalDetailed=new SlWithdrawalDetailed();
		BeanUtil.copyProperties(param,slWithdrawalDetailed);
		LambdaQueryWrapper<SlWithdrawalDetailed> wrapper = new LambdaQueryWrapper<>();
		if (ObjectUtils.isNotEmpty(param.getSettlementBeginTime()) || ObjectUtils.isNotEmpty(param.getSettlementEndTime())) {
			wrapper.between(SlWithdrawalDetailed::getSettlementTime, param.getSettlementBeginTime(), param.getSettlementEndTime());
		}
		if (ObjectUtils.isNotEmpty(param.getBeginTime()) || ObjectUtils.isNotEmpty(param.getEndTime())) {
			wrapper.between(SlWithdrawalDetailed::getWithdrawalTime, param.getBeginTime(), param.getEndTime());
		}
		if (ObjectUtils.isNotEmpty(param.getWithdrawalNo())) {
			wrapper.eq(SlWithdrawalDetailed::getWithdrawalNo, param.getWithdrawalNo());
		}
		if (ObjectUtils.isNotEmpty(param.getWalletOrderId())) {
			wrapper.eq(SlWithdrawalDetailed::getWalletOrderId, param.getWalletOrderId());
		}
		if (ObjectUtils.isNotEmpty(param.getWithdrawalStatus())) {
			wrapper.eq(SlWithdrawalDetailed::getWithdrawalStatus, param.getWithdrawalStatus());
		}
		if (ObjectUtils.isNotEmpty(param.getUserId())) {
			wrapper.eq(SlWithdrawalDetailed::getUserId, param.getUserId());
		}
		wrapper.orderByDesc(SlWithdrawalDetailed::getId);
		slWithdrawalDetailed.setSumStatus(Convert.toStr(HpcEnum.DRAWING_STATUS.getCode()));
		BigDecimal drawingAmount=slWithdrawalDetailedMapper.sumAmount(slWithdrawalDetailed);
		slWithdrawalDetailed.setSumStatus(Convert.toStr(HpcEnum.DRAWING_STATUS_OK.getCode()));
		BigDecimal drawFinishAmount=slWithdrawalDetailedMapper.sumAmount(slWithdrawalDetailed);
		List<SlWithdrawalDetailed> list = slWithdrawalDetailedMapper.selectList(wrapper);
		try {
			List<List<Object>> rows = new ArrayList();
			ExcelData data = new ExcelData();
			//sheet表名称
			data.setName("商家提现明细导出");
			List<String> firstTitles=new ArrayList<>();
			firstTitles.add("所有店铺剩余可提现余额汇总");
			firstTitles.add(Convert.toStr(drawingAmount.add(drawFinishAmount)));
			firstTitles.add("提现成功汇总");
			firstTitles.add(Convert.toStr(drawFinishAmount));
			firstTitles.add("提现中汇总");
			firstTitles.add(Convert.toStr(drawingAmount));
			data.setTitles(firstTitles);
			//表头
			List<Object> titles = new ArrayList();
			titles.add("编号");
			titles.add("申请时间");
			titles.add("店铺名称");
			titles.add("商家用户ID");
			titles.add("提现单号");
			titles.add("提现流水号");
			titles.add("提现金额");
			titles.add("提现到");
			titles.add("银行卡号");
			titles.add("提现状态");
			titles.add("提现完成时间");
			titles.add("累计成功提现金额");
			titles.add("店铺可提现余额");
			rows.add(titles);
			for (SlWithdrawalDetailed details : list) {
				List<Object> row1 = new ArrayList();
				row1.add(details.getId());
				row1.add(DateUtils.formatDate(details.getCreatedTime(),"yyyy-MM-dd HH:mm:ss"));
				row1.add(details.getShopName());
				row1.add(details.getUserId());
				row1.add(details.getWalletOrderId());
				row1.add(details.getWithdrawalNo());
				row1.add(details.getTotalAmount());
				row1.add(details.getBankName());
				row1.add(details.getBankCardCode());
				String withdrawalStatus="提现中";
				if (ObjectUtils.isNotEmpty(details.getWithdrawalStatus())) {
					if(details.getWithdrawalStatus().equals("1")){
						withdrawalStatus="提现完成";
					}
				}
				row1.add(withdrawalStatus);
				String settlementTime=null;
				if(details.getSettlementTime()!=null){
					settlementTime=DateUtils.formatDate(details.getSettlementTime(),"yyyy-MM-dd HH:mm:ss");
				}
				row1.add(settlementTime);
				row1.add(details.getAddTotalAmount());
				row1.add(details.getShopAvailableAmount());
				rows.add(row1);
			}
			data.setRows(rows);
			ExportExcelUtils.exportExcel(response, "提现收入明细导出.xlsx", data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}